import { ref } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
import { router } from '@/router'
import { useCookies } from '@vueuse/integrations/useCookies'

export const useTabList = () => {
  const route = useRoute()
  const cookie = useCookies()
  const editableTabsValue = ref(route.path) //  当前激活的标签页
  const editableTabs = ref([
    {
      title: '后台首页',
      path: '/'
    }
  ])
  // 监听路由变化
  onBeforeRouteUpdate(to => {
    const index = editableTabs.value.findIndex(tab => tab.path === to.path)
    if (index === -1) {
      addTab(to)
    }
    editableTabsValue.value = to.path
  })
  // 自动添加标签tabs
  const addTab = to => {
    editableTabs.value.push({
      title: to.meta.title,
      path: to.path
    })
    cookie.set('tabList', editableTabs.value)
  }
  // tabs点击跳转
  const tabChange = a => {
    editableTabsValue.value = a
    router.push(a)
  }
  // tabs点击删除
  const removeTab = t => {
    let tabs = editableTabs.value
    let a = editableTabsValue.value
    if (a == t) {
      tabs.forEach((tab, index) => {
        if (tab.path == t) {
          let nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            a = nextTab.path
          }
        }
      })
    }
    editableTabsValue.value = a
    editableTabs.value = editableTabs.value.filter(tab => tab.path != t)
    cookie.set('tabList', editableTabs.value)
  }
  // 初始化标签导航列表
  const initTabList = () => {
    let tbs = cookie.get('tabList')
    if (tbs) {
      editableTabs.value = tbs
    }
  }
  initTabList()
  // 处理全部关闭和关闭其他
  const handleClose = c => {
    if (c === 'clearOther') {
      // 过滤当前标签（只剩下首页和当前页）
      editableTabs.value = editableTabs.value.filter(
        tab => tab.path == '/' || tab.path == editableTabsValue.value
      )
    } else if (c === 'clearAll') {
      // 切换回到首页
      editableTabsValue.value = '/'
      // 过滤只剩下首页
      editableTabs.value = [
        {
          title: '后台首页',
          path: '/'
        }
      ]
    }
    cookie.set('tabList', editableTabs.value)
  }
  return {
    editableTabsValue,
    editableTabs,
    tabChange,
    removeTab,
    handleClose
  }
}
